package com.example.reactor;

import reactor.core.publisher.Mono;

public class Practice12 {

    public Mono<Integer> buy(Long uid, Long productId) {
        return checkCardPurchased(uid, productId)
                .flatMap(purchased -> {
                    if (!purchased) {
                        return Mono.error(new Exception("Card not purchased"));
                    }
                    return Mono.just(1);  // 假设购买成功返回 1
                })
                // 捕获异常并返回自定义消息
                .onErrorResume(e -> {
                    System.err.println("Error during buy: " + e.getMessage());
                    return Mono.just(-1);  // 出现异常时返回 -1 表示失败
                });
    }

    public Mono<Boolean> checkCardPurchased(Long uid, Long productId) {
        return Mono.defer(() -> {
            if (productId == null) {
                return Mono.error(new Exception("ProductId is invalid"));
            }
            // 模拟卡片是否已购买的情况
            return Mono.just(productId % 2 == 0);  // 偶数表示已购买，奇数未购买
        });
    }

    public static void main(String[] args) {
        Practice12 service = new Practice12();

        // 测试不同的 productId
//        System.out.println("Testing with valid productId (even number):");
//        service.buy(1L, 2L).subscribe(result -> System.out.println("Result: " + result));

//        System.out.println("\nTesting with invalid productId (odd number):");
//        service.buy(1L, 3L).subscribe(result -> System.out.println("Result: " + result));

        System.out.println("\nTesting with null productId:");
        service.buy(1L, null).subscribe(result -> System.out.println("Result: " + result));
    }


}
